package com.tang.lts.core.store;

import com.tang.lts.core.cluster.Config;
import com.tang.lts.core.constant.ExtConfig;
import lombok.SneakyThrows;

import java.io.*;

/**
 * @author Tang
 * @classname JdbcAbstractAccess
 * @description [  ]
 * @date 2022/5/7 22:54
 */
public abstract class JdbcAbstractAccess {

    private SqlTemplate sqlTemplate;

    private Config config;

    public JdbcAbstractAccess(Config config) {
        this.sqlTemplate = SqlTemplateFactory.getSqlTemplate(config);
        this.config = config;
    }

    public SqlTemplate getSqlTemplate() {
        return sqlTemplate;
    }

    @SneakyThrows
    protected String readSqlFile(String path) {
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(path);
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        StringWriter writer = new StringWriter();
        int read = 0;
        String data = null;
        while ((data = reader.readLine()) != null) {
            writer.append(data);
        }
        reader.close();
        return writer.toString();
    }

    protected String readSqlFile(String path, String tableName) {
        String sql = readSqlFile(path);
        return sql.replace("{tableName}", tableName);
    }

    protected void createTable(String sql) {
        if (config.getParameter(ExtConfig.NEED_CREATE_DB_TABLE, true)) {
            getSqlTemplate().createTable(sql);
        }
    }

}